package com.demo.conf;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;
import org.springframework.util.StreamUtils;
/**
 * 封装request 
 * 以解决request.getInputStream()只能用一次(springboot 封装时已调用此方法后续获取为空)
 *
 */
public class StreamRequestWrapper extends HttpServletRequestWrapper{
	
	private static Logger log = Logger.getLogger(StreamRequestWrapper.class);

    private byte[] stream;
    
	public StreamRequestWrapper(HttpServletRequest request) {
		super(request);
		initStream(request);
	}
	public void initStream(ServletRequest request){
		try {
			InputStream in = request.getInputStream();
			if(in==null) return;
			stream = StreamUtils.copyToByteArray(in);
		} catch (Exception e) {
			log.error("wrapper 初始化stream失败");
		}
	}
	
	/**
	 * 重载getInputStream方法
	 */
	@Override
    public ServletInputStream getInputStream ()
        throws IOException {
		if(stream==null){
			initStream(getRequest());
		}
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stream);
        return new ServletInputStream() {
            public int read ()
                    throws IOException {
                    return byteArrayInputStream.read();
                }

    			@Override
    			public boolean isFinished() {
    				// TODO Auto-generated method stub
    				return false;
    			}

    			@Override
    			public boolean isReady() {
    				// TODO Auto-generated method stub
    				return false;
    			}

    			@Override
    			public void setReadListener(ReadListener listener) {
    				// TODO Auto-generated method stub
    				
    			}
            };
    }

}
